import { GATEWAY_URL } from "@/lib/env";
import { ItemCategory } from "@/shared/item";
import { useState, useEffect } from "react";

const useCategories = () => {
  const [categories, setCategories] = useState<ItemCategory[]>([]);
  const [selected, setSelected] = useState<number>(0);

  const fetchCategories = async () => {
    try {
      const response = await fetch(`${GATEWAY_URL}/items/categories`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      const data = await response.json();
      setCategories(data);
      setSelected(data[0].id);
    } catch (error) {
      console.error("Error fetching categories:", error);
    }
  };

  useEffect(() => {
    fetchCategories();
  }, []);

  return { categories, selected, setSelected, refresh: fetchCategories };
};

export default useCategories;
